package com.example.springboot_mongo.controller;

import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.*;

@RestController
public class ImgController {
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上传并且预览
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/save/{imgName}")
    public void testMongoSaveImg(@PathVariable(name = "imgName",required = true) String imgName, HttpServletResponse httpServletResponse) throws Exception {
        if(imgName==null||imgName==""){
            System.out.println("图片名称不能为空");
            return;
        }
        ObjectId objectId = gridFsTemplate.store(new FileInputStream(new File("D:\\360Downloads\\"+imgName+".jpg")), "abc");
        System.out.println(objectId.toString());
        //返回浏览器
        testGetImg(objectId.toString(),httpServletResponse);
    }

    /**
     * 查看图片
     * @param id
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/query/{id}")
    public void testGetImg( @PathVariable(name = "id",required = true) String id, HttpServletResponse httpServletResponse) throws Exception{
        long start=System.currentTimeMillis();
        httpServletResponse.setContentType("image/jpg");
        System.out.println(id);
        ServletOutputStream out = httpServletResponse.getOutputStream();
        GridFSFile result = gridFsTemplate
                .findOne(new Query(Criteria.where("_id").is(new ObjectId(id))));
        System.out.println(result.toString());
        GridFsResource gridFsResource = gridFsTemplate.getResource(result);
        System.out.println(gridFsResource);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        InputStream stream = gridFsResource.getInputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n =stream .read(buffer))) {
            output.write(buffer, 0, n);
        }
        out.write(output.toByteArray());
        out.flush();
        out.close();
        long end=System.currentTimeMillis();
        System.out.println("总共耗时："+(end-start));
    }

    @RequestMapping("/delete")
    public Object delete(){
        gridFsTemplate.delete(new Query());
        return "delete successful";
    }

    /**
     * db.runCommand( { compact : 'fs.chunks' } ) gridFsTemplate不支持
     * @return
     */
    @RequestMapping("/remove")
    public Object removeDiskData(){
        mongoTemplate.executeCommand("{compact: 'student' }");
        mongoTemplate.executeCommand("{compact: 'user' }");
        mongoTemplate.executeCommand("{compact: 'user_1' }");
        return "successful";
    }

}
